<template>
  <el-dialog v-if="visible" :visible="visible" width="500px" title="创建场次" :append-to-body="true" :close-on-click-modal="false" @close="cancel">
    <el-form ref="form" v-loading="loading" :model="form" :rules="formRules" label-width="120px" label-position="left">
      <el-form-item label="演出时间" prop="show_time">
        <el-date-picker
          v-model="form.show_time"
          type="datetime"
          format="yyyy-MM-dd HH:mm"
          value-format="yyyy-MM-dd HH:mm:00"
          default-time="00:00:00"
          placeholder="请选择演出时间"
          style="width: 100%"
          @change="$refs.form.validateField(['show_time'])"
        />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="form.sort" :clearable="true" placeholder="请输入排序" @clear="$refs.form.validateField(['sort'])" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :label="0">显示</el-radio>
          <el-radio :label="1">隐藏</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="cancel">取消</el-button>
      <el-button v-loading="loading" type="primary" @click="enter">确认</el-button>
    </template>
  </el-dialog>
</template>
<script>
import { addShowScene } from '@/api/show'
export default {
  name: 'Create',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    showId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      loading: false,
      form: {
        show_id: this.showId,
        show_time: '',
        status: 0,
        sort: ''
      },
      formRules: {
        show_time: [
          {
            trigger: 'blur',
            validator(rule, value, callback) {
              if (typeof value !== 'string') {
                return callback(new Error('演出时间不能为空'))
              }
              if (value.trim().length === 0) {
                return callback(new Error('演出时间不能为空'))
              }
              return callback()
            }
          }
        ],
        sort: [
          {
            trigger: 'blur',
            validator(rule, value, callback) {
              if (value.trim().length === 0) {
                return callback()
              }
              if (!/^\d+$/.test(value)) {
                return callback(new Error('请输入数值'))
              }
              return callback()
            }
          }
        ]
      }
    }
  },
  methods: {
    async enter() {
      try {
        await this.$refs.form.validate()
        try {
          this.loading = true
          await addShowScene(this.form)
          this.loading = false
          this.$emit('enter')
        } catch (error) {
          this.$errorMessage()
          this.loading = false
        }
      } catch (error) {
        this.$errorMessage('表单输入有误')
      }
    },
    cancel() {
      this.$emit('cancel')
    }
  }
}
</script>
